package com.tgy.MyFlowable.workflow.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.BetweenFormater;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ctsi.core.common.api.Result;
import com.ctsi.core.common.util.$;
import com.ctsi.core.common.util.SecurityUtil;
import com.ctsi.core.common.util.StringPool;
import com.ctsi.core.database.util.PageUtil;
import com.ctsi.system.service.IUserService;
import com.ctsi.workflow.dto.FlwDoneTaskDTO;
import com.ctsi.workflow.service.IFlwDoneTaskService;
import com.ctsi.workflow.service.IFlwInstanceService;
import com.ctsi.workflow.vo.FlwDoneTaskVO;
import com.ctsi.workflow.vo.FlwInstanceVO;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.HistoryService;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 已办事项业务实现类
 *
 * @version 1.0
 * @author: wang xiao xiang
 * @date: 2021/8/8 19:27
 */
@Service
@RequiredArgsConstructor
public class FlwDoneTaskServiceImpl implements IFlwDoneTaskService {
    private final HistoryService historyService;

    private final IFlwInstanceService flwInstanceService;

    @Autowired
    private IUserService userService;

    @Autowired
    private HttpServletRequest request;

    @Override
    public IPage<FlwDoneTaskVO> page(FlwDoneTaskDTO flwDoneTaskDTO) {
        HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery();
        //Long userId = MarsContextHolder.getUserId();
        Long userId = SecurityUtil.getUsername(request).getId();
        historicTaskInstanceQuery.taskAssignee($.toStr(userId));
        historicTaskInstanceQuery.finished();
        //根据任务办理时间倒序，最新办完的在最上面
        historicTaskInstanceQuery.orderByHistoricTaskInstanceEndTime().desc();

        if ($.isNotNull(flwDoneTaskDTO)) {
            //流程名称模糊查询
            if ($.isNotEmpty(flwDoneTaskDTO.getProcessName())) {
                historicTaskInstanceQuery.processDefinitionNameLike(StringPool.PERCENT + flwDoneTaskDTO.getProcessName() + StringPool.PERCENT);
            }
            //任务名称模糊查询
            if ($.isNotEmpty(flwDoneTaskDTO.getName())) {
                historicTaskInstanceQuery.taskNameLike(StringPool.PERCENT + flwDoneTaskDTO.getName() + StringPool.PERCENT);
            }
            //流程分类查询
            if ($.isNotEmpty(flwDoneTaskDTO.getCategory())) {
                historicTaskInstanceQuery.processCategoryIn(CollectionUtil.newHashSet(flwDoneTaskDTO.getCategory()));
            }
            //创建时间范围查询
            if (ObjectUtil.isAllNotEmpty(flwDoneTaskDTO.getStartDate(), flwDoneTaskDTO.getEndDate())) {
                historicTaskInstanceQuery.taskCreatedAfter(DateUtil.parseDateTime(flwDoneTaskDTO.getStartDate()))
                        .taskCreatedBefore(DateUtil.parseDateTime(flwDoneTaskDTO.getEndDate()));
            }
            //优先级查询
            if ($.isNotEmpty(flwDoneTaskDTO.getPriority())) {
                historicTaskInstanceQuery.taskPriority(flwDoneTaskDTO.getPriority());
            }
        }
        Page<FlwDoneTaskVO> defaultPage = PageUtil.getPage(flwDoneTaskDTO);
        long current = defaultPage.getCurrent();
        long size = defaultPage.getSize();
        List<HistoricTaskInstance> taskList = historicTaskInstanceQuery
                .listPage(Convert.toInt((current - 1) * size), Convert.toInt(size));
        defaultPage.setTotal(historicTaskInstanceQuery.count());
        List<FlwDoneTaskVO> collect = taskList.stream().map(historicTaskInstance -> convertToDoneTaskVO(historicTaskInstance)).collect(Collectors.toList());
        defaultPage.setRecords(collect);
        return defaultPage;
    }

    /**
     * 将单个已办任务结果转换为自定义结果
     *
     * @param historicTaskInstance
     * @return
     */
    private FlwDoneTaskVO convertToDoneTaskVO(HistoricTaskInstance historicTaskInstance) {
        FlwDoneTaskVO flwDoneTaskVO = $.copy(historicTaskInstance, FlwDoneTaskVO.class);
        flwDoneTaskVO.setActivityId(historicTaskInstance.getTaskDefinitionKey());
        flwDoneTaskVO.setAssigneeName(Result.data(userService.getById($.toLong(historicTaskInstance.getAssignee()))).getData().getAccount());
        flwDoneTaskVO.setAssigneeInfo("处理人:" + flwDoneTaskVO.getAssigneeName());
        flwDoneTaskVO.setFormatCreateTime($.formatPastTime(historicTaskInstance.getCreateTime()));
        flwDoneTaskVO.setFormatEndTime($.formatPastTime(historicTaskInstance.getEndTime()));
        flwDoneTaskVO.setDuration(DateUtil.formatBetween(historicTaskInstance.getDurationInMillis(), BetweenFormater.Level.SECOND));
        FlwInstanceVO flwInstanceVO = flwInstanceService.detail(historicTaskInstance.getProcessInstanceId());
        flwDoneTaskVO.setProcIns(flwInstanceVO);
        return flwDoneTaskVO;
    }
}
